<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" @close="resetForm" destroy-on-close>

    <el-form :model="stuffForm" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="上级目录" prop="parentId">
        <stuff-dir-select v-model="stuffForm.parentId" />
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="stuffForm.title"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <Editor :value.sync="stuffForm.content"/>
      </el-form-item>     
      
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/common/api';

import StuffDirSelect from '@/components/admin/StuffDirSelect';
import Editor from '@/components/admin/Editor';

export default {
  name: 'FileStuffDialog',
  props: {},

  components: {
    StuffDirSelect,
    Editor
  },

  data() {
    return {
      loading: false,
      dialogVisible: false,

      stuffForm: {
        parentId: null,
        title: '',
        content: '',
        stuffType: 'md'
      },
      rules: {
        parentId: [
          { required: true, message: '请选择上级目录', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.stuffForm.id ? '编辑素材' : '添加素材'
    }
  },

  methods: {
    async open(data) {
      if (data && data.id) {
        try {
          this.loading = true
          const {data: detail} = await api.admin_getStuffDetail(data.id)
          this.stuffForm = Object.assign({}, this.stuffForm, detail.data)
        } finally {
          this.loading = false
        }
      } else {
        this.stuffForm = Object.assign({}, this.stuffForm, data)
      }
      this.dialogVisible = true      
    },

    resetForm() {
      this.$refs.formRef?.resetFields()
      this.stuffForm = {
        parentId: null,
        title: '',
        content: '',
        stuffType: 'md'
      }
    },

    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return

        try {
          this.loading = true
          const {data} = await api.admin_saveStuff(this.stuffForm)
          this.$message.success('保存成功')
          this.dialogVisible = false

          this.$emit('success', data.data)
        } finally {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped>
.w-full {
  width: 100%;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>